import pickle


        
tOut = open("results.pk","rb")
results = pickle.load(tOut)

print "Parsing Time"

import datetime

def bydtposted(x,y):
    xDate = parseToDatetime(x["dtposted"]).date()
    yDate = parseToDatetime(y["dtposted"]).date()
    if xDate < yDate: return -1
    if xDate == yDate: return 0
    
    return 1
    

def parseToDatetime(str):
    return datetime.datetime.strptime(str,"%Y%m%d%H%M%S")
    
    (str[:4],str[4:6],str[6:8],str[8:10],str[10:12],str[12:14])

def parseBankAccounts(ofxBody):
    if hasattr(ofxBody["bankmsgsrsv1"]["stmttrnrs"],"append"):
        for st in ofxBody["bankmsgsrsv1"]["stmttrnrs"]:
            bankAccount = st["stmtrs"]["bankacctfrom"]
            print bankAccount
            
            translist = st["stmtrs"]["banktranlist"]
            print "From: %s To: %s" % ( parseToDatetime(translist.get("dtstart")), parseToDatetime(translist.get("dtend")))
            
            topDate = parseToDatetime(translist.get("dtstart"))
            debits = 0
            credits = 0
            totalDebits = []
            totalCredits = []
            sortTrxs = sorted(translist["stmttrn"],bydtposted)
            
            
            for trx in sortTrxs:
                dtposted = parseToDatetime(trx["dtposted"])
               
                if topDate.date() != dtposted.date():
                    topDate = dtposted
                    print dtposted.date(), "Credit: [%09s] Debit [%09s] - NET %09s" % (credits, debits, credits+debits)
                    debits = credits = 0
                                                    
                if float(trx["trnamt"]) > 0:
                    credits += float(trx["trnamt"])
                    totalCredits.append(float(trx["trnamt"]))
                else:
                    debits += float(trx["trnamt"])
                    totalDebits.append(float(trx["trnamt"]))
                    
                
            print "Summary"
            print "Daily averages Credit[%012s] Debit[%012s]" % (sum(totalCredits)/ len(totalCredits), sum(totalDebits)/ len(totalDebits))
            print "Totals:        Credit[%012s] Debit[%012s]" % (sum(totalCredits), sum(totalDebits) ) 
            print
        print
            
        
parseBankAccounts(results[0]["ofx"])